/**
 * EmployeeDAO class.
 */
package pits.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import pits.dto.EmployeeDTO;
import pits.form.EditEmployeeInfoForm;
import pits.util.Constants;

/**
 * @author ltd
 * 
 */
public class EmployeeDAO {

	/**
	 * log property
	 */
	public static Logger log = Logger.getLogger("EmployeeDAO");

	/**
	 * Get the information of one specify user.
	 * 
	 * @param empID
	 * @return EmployeeDTO if user is exist else null
	 */
	public List<EmployeeDTO> getEmployeeInfo(int empID) {
		log.info("getEmployeeInfo start");
		final EmployeeDTO dto = new EmployeeDTO();
		final List<EmployeeDTO> result = new ArrayList<EmployeeDTO>();
		Connection conn = null;
		String query = Constants.BLANK_VALUE;
		ResultSet rs = null;
		PreparedStatement pStat = null;

		try {
			query = "select * " + "from employee " + "where EmpID=? and isDeleted=0";
			conn = pits.util.Connection.getConnection();
			pStat = conn.prepareStatement(query);
			pStat.setInt(1, empID);
			rs = pStat.executeQuery();
			if (rs.next()) {
				dto.setEmpID(rs.getInt("EmpID"));
				dto.setName(rs.getString("Name"));
				dto.setBirthday(rs.getString("Birthday"));
				dto.setAddress(rs.getString("Address"));
				dto.setEmail(rs.getString("Email"));
				dto.setGender(rs.getByte("Gender"));
				dto.setPhone(rs.getString("Phone"));
				result.add(dto);
			}
		} catch (final Exception sqlEx) {
			log.error("EmployeeDAO.getEmployeeInfo " + sqlEx);
		} finally {
			try {
				rs.close();
				pStat.close();
				conn.close();
			} catch (final SQLException sqlEx) {
				log.error("EmployeeDAO.getEmployeeInfo " + sqlEx);
			}
		}

		return result;
	}

	public void updateEmployeeInfo(int empID, EditEmployeeInfoForm formEmp) {

		log.info("updateEmployeeInfo start");

		Connection conn = null;
		String query = Constants.BLANK_VALUE;
		PreparedStatement pStat = null;

		try {
			query = "update employee " + "set Name=?, Birthday=?, Address=?, Phone=?, Email=?, Gender=? "
			        + "where EmpID=? and isDeleted=0";
			conn = pits.util.Connection.getConnection();
			pStat = conn.prepareStatement(query);
			pStat.setString(1, formEmp.getName());
			pStat.setString(2, formEmp.getBirthday());
			pStat.setString(3, formEmp.getAddress());
			pStat.setString(4, formEmp.getPhone());
			pStat.setString(5, formEmp.getEmail());
			pStat.setByte(6, formEmp.getGender());
			pStat.setInt(7, empID);
			pStat.executeUpdate();
		} catch (final Exception sqlEx) {
			log.error("EmployeeDAO.updateEmployeeInfo " + sqlEx);
		} finally {
			try {
				pStat.close();
				conn.close();
			} catch (final SQLException sqlEx) {
				log.error("EmplooyeeDAO.updateEmployeeInfo " + sqlEx);
			}
		}

	}
}
